const express = require('express');
const Adoption = require('../models/adoption');
const { authMiddleware, adminMiddleware } = require('../middleware/auth');
const { pool } = require('../config/db');

const router = express.Router();

// @route   POST api/adoptions/apply
// @desc    Submit an adoption application
// @access  Private
router.post('/apply', authMiddleware, async (req, res) => {
  try {
    const {
      pet_id,
      reason_for_adoption,
      living_situation,
      previous_pet_experience,
      additional_notes
    } = req.body;

    const applicationData = {
      user_id: req.user.id,
      pet_id,
      reason_for_adoption,
      living_situation,
      previous_pet_experience,
      additional_notes
    };

    const application = await Adoption.createApplication(applicationData);
    res.status(201).json(application);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ message: err.message });
  }
});

// @route   GET api/adoptions/my-applications
// @desc    Get all applications by the logged-in user
// @access  Private
router.get('/my-applications', authMiddleware, async (req, res) => {
  try {
    const applications = await Adoption.getApplicationsByUser(req.user.id);
    res.json(applications);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/my-pets
// @desc    获取用户已领养的宠物
// @access  Private
router.get('/my-pets', authMiddleware, async (req, res) => {
  try {
    const userId = req.user.id;

    // 查询当前用户所有status为approved的申请，并关联宠物信息
    const query = `
      SELECT 
        p.*,
        a.approval_date as adoption_date,
        a.id as application_id,
        a.status as application_status
      FROM adoption_applications a
      JOIN pets p ON a.pet_id = p.id
      WHERE a.user_id = ?
        AND a.status = 'approved'
      ORDER BY a.approval_date DESC
    `;

    const [adoptedPets] = await pool.query(query, [userId]);

    // 处理图片URL
    const processedPets = adoptedPets.map(pet => ({
      ...pet,
      image_url: pet.image_url
        ? (pet.image_url.startsWith('http://') || pet.image_url.startsWith('https://')
           ? pet.image_url
           : `/uploads/pets/${pet.image_url}`)
        : 'https://images.unsplash.com/photo-1425082661705-1834bfd09dca?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'
    }));

    res.json(processedPets);
  } catch (err) {
    console.error('获取已领养宠物失败:', err);
    res.status(500).json({ message: '服务器错误', error: err.message });
  }
});

// @route   GET api/adoptions/applications
// @desc    Get all applications (admin only)
// @access  Private/Admin
router.get('/applications', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { status, page = 1, limit = 10 } = req.query;
    const result = await Adoption.getAllApplications(status, page, limit);
    res.json(result);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/records
// @desc    Get all adoption records (admin only)
// @access  Private/Admin
router.get('/records', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const result = await Adoption.getAdoptionRecords(page, limit);
    res.json(result);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/applications/:id
// @desc    Get application by ID
// @access  Private
router.get('/applications/:id', authMiddleware, async (req, res) => {
  try {
    const application = await Adoption.getApplicationById(req.params.id);
    
    if (!application) {
      return res.status(404).json({ message: 'Application not found' });
    }
    
    // Only admin or the applicant can view the application
    if (!req.user.is_admin && application.user_id !== req.user.id) {
      return res.status(403).json({ message: 'Not authorized to view this application' });
    }
    
    res.json(application);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/pet/:id
// @desc    Get all applications for a pet (admin only)
// @access  Private/Admin
router.get('/pet/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const applications = await Adoption.getApplicationsByPet(req.params.id);
    res.json(applications);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
});

// @route   PUT api/adoptions/applications/:id
// @desc    Update application status (admin only)
// @access  Private/Admin
router.put('/applications/:id', [authMiddleware, adminMiddleware], async (req, res) => {
  try {
    const { status } = req.body;
    
    // 允许所有枚举值，包括'cancelled'
    if (!['pending', 'approved', 'rejected', 'cancelled'].includes(status)) {
      return res.status(400).json({ message: 'Invalid status' });
    }
    
    const updatedApplication = await Adoption.updateApplicationStatus(
      req.params.id, 
      status,
      req.user.id
    );
    
    res.json(updatedApplication);
  } catch (err) {
    console.error('更新领养申请状态失败:', err); // 输出详细错误日志
    res.status(500).send('Server error');
  }
});

// @route   GET api/adoptions/count
// @desc    获取各状态申请的数量
// @access  私有(管理员)
router.get('/count', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT COUNT(*) as count FROM adoption_applications';
    const queryParams = [];
    
    if (status) {
      query += ' WHERE status = ?';
      queryParams.push(status);
    }
    
    const [rows] = await pool.query(query, queryParams);
    res.json({ count: rows[0].count });
  } catch (err) {
    console.error('获取申请数量失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   GET api/adoptions/trends
// @desc    获取最近30天的申请趋势数据
// @access  私有(管理员)
router.get('/trends', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    // 计算30天前的日期
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const thirtyDaysAgoStr = thirtyDaysAgo.toISOString().substring(0, 10);
    
    // 获取最近30天的申请数据
    const [recentApplications] = await pool.query(
      `SELECT application_date FROM adoption_applications
       WHERE application_date >= ?
       ORDER BY application_date DESC`,
      [thirtyDaysAgoStr]
    );
    
    // 按日期分组统计申请数量
    const applicationsByDate = {};
    const dates = [];
    const counts = [];
    
    // 初始化过去30天的日期
    for (let i = 29; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const dateString = `${date.getMonth() + 1}/${date.getDate()}`;
      dates.push(dateString);
      applicationsByDate[dateString] = 0;
    }
    
    // 统计每天的申请数量
    recentApplications.forEach(application => {
      const date = new Date(application.application_date);
      const dateString = `${date.getMonth() + 1}/${date.getDate()}`;
      if (applicationsByDate[dateString] !== undefined) {
        applicationsByDate[dateString]++;
      }
    });
    
    // 转换为数组
    dates.forEach(date => {
      counts.push(applicationsByDate[date] || 0);
    });
    
    res.json({
      applicationTrend: {
        dates,
        counts
      }
    });
  } catch (err) {
    console.error('获取申请趋势数据失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// @route   GET api/adoptions/pet/:id/count
// @desc    获取指定宠物的申请数量
// @access  私有(管理员)
router.get('/pet/:id/count', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    const count = await Adoption.getApplicationsCountByPet(req.params.id);
    res.json({ count });
  } catch (err) {
    console.error('获取宠物申请数量失败:', err);
    res.status(500).json({ message: '服务器错误' });
  }
});

// Add new public route for checking pet application count
// @route   GET api/adoptions/pet/:id/applications/count
// @desc    Get application count for a specific pet (public)
// @access  Public
router.get('/pet/:id/applications/count', async (req, res) => {
  try {
    const count = await Adoption.getApplicationsCountByPet(req.params.id);
    res.json({ count });
  } catch (err) {
    console.error('Getting pet application count failed:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   PUT /api/adoptions/cancel/:id
// @desc    取消领养申请
// @access  Private
router.put('/cancel/:id', authMiddleware, async (req, res) => {
  try {
    const applicationId = req.params.id;
    const userId = req.user.id;

    console.log(`接收到用户 ${userId} 的取消领养请求，申请ID: ${applicationId}`);

    // 查找领养申请
    const [applications] = await pool.query(
      'SELECT id, user_id, status FROM adoption_applications WHERE id = ?', 
      [applicationId]
    );

    const application = applications[0];

    // 检查申请是否存在
    if (!application) {
      console.warn(`申请ID ${applicationId} 未找到`);
      return res.status(404).json({ message: '领养申请不存在' });
    }

    console.log(`找到申请，当前状态: ${application.status}, 提交用户ID: ${application.user_id}`);

    // 检查当前用户是否是该申请的提交者
    if (application.user_id !== userId) {
      console.warn(`用户 ${userId} 无权取消申请 ${applicationId}，该申请属于用户 ${application.user_id}`);
      return res.status(403).json({ message: '无权取消此领养申请' });
    }

    // 检查申请当前状态是否允许取消 (例如：只能取消已批准或待处理的)
    if (application.status !== 'pending' && application.status !== 'approved') {
         console.warn(`申请 ${applicationId} 状态为 ${application.status}，不允许取消`);
         return res.status(400).json({ message: `当前申请状态为 ${application.status}，无法取消。` });
    }

    // 更新申请状态为 'cancelled'
    console.log(`更新申请 ${applicationId} 状态为 'cancelled'`);
    await pool.query(
      'UPDATE adoption_applications SET status = \'cancelled\' WHERE id = ?', 
      [applicationId]
    );
    console.log(`申请 ${applicationId} 状态更新成功`);

    res.json({ message: '领养申请已取消' });

  } catch (err) {
    console.error('取消领养失败:', err);
    res.status(500).json({ message: '服务器错误，请稍后重试' });
  }
});

module.exports = router; 